﻿
function checkListItemTemplate(itemPromise) {

    return itemPromise.then(function (item) {
        var _template = document.createElement("div");
        var _container = document.createElement("div");
        _container.className = "-check-item-container";
        _container.id = "-check-item-" + item.data.id;
        _template.appendChild(_container);

        var _checkBox = document.createElement("div");
        if (item.data.isChecked) {
            _checkBox.className = "checkbox checked";
        }
        else {
            _checkBox.className = "checkbox";
        }

        var _name = document.createElement("div");
        _name.className = "-item-label";
        _name.innerText = item.data.itemname;

        _container.appendChild(_checkBox);
        _container.appendChild(_name);

        return _template;
    });
}

function checkListTemplate(itemPromise) {

    return itemPromise.then(function (item) {
        var _template = document.createElement("div");
        var _container = document.createElement("div");
        _container.className = "-check-list-container";
        _container.id = "-check-list-" + item.data.id;
        _template.appendChild(_container);

        var _name = document.createElement("span");
        _name.className = "-check-list-name";
        _name.innerText = item.data.name;

        var _arrow = document.createElement("span");
        _arrow.className = "-check-list-arrow";
        _arrow.innerText = '>';

        _container.appendChild(_name);
        _container.appendChild(_arrow);

        return _template;
    });
}

WinJS.Utilities.markSupportedForProcessing(checkListItemTemplate);
WinJS.Utilities.markSupportedForProcessing(checkListTemplate);

(function () {
    "use strict";

    var listStore = Ext.StoreMgr.lookup('AAWE.App.List.Store.CheckListStore');
    var itemStore = Ext.StoreMgr.lookup('AAWE.App.List.Store.CheckListItemStore');
    var checkListsControl;
    var checkLists;
    var checkItemsControl;
    var checkItems;
    
    var currentListId = -1;
    var currentListName;
    var selectedLists = [];
    var selectedItems = [];

    var itemsShowed = false;
    var listCount = 0;
    var itemCount = 0;

    var appBar;
    var addListBtn;
    var addItemBtn;
    var clearSelectBtn;
    var editBtn;
    var deleteBtn;

    WinJS.UI.Pages.define("/pages/check-list/main.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            WinJS.Resources.processAll();
            initAppBar();
            initHandler();

            checkListsControl = document.getElementById("-check-list").winControl;
            checkItemsControl = document.getElementById("-check-item-list").winControl;
            
            showLists();
        }
    });

    // event handlers
    function checkListInvoked(eventObject) {
        eventObject.detail.itemPromise.done(function (invokedItem) {
            currentListId = invokedItem.data.id;
            currentListName = invokedItem.data.name;
            itemsShowed = true;
            $('.-check-list-arrow').hide();
            $('#-check-list-' + currentListId + ' .-check-list-arrow').show();
            showItemList(currentListId);
            adjustAppBar(listCount + itemCount);
        });
    }

    function checkListSelectionchanged() {
        try {
            listCount = checkListsControl.selection.count();
            itemCount = checkItemsControl.selection.count();

            if (listCount > 0 && itemCount > 0) {
                checkItemsControl.selection.clear();
            }
            else {
                adjustAppBar(listCount + itemCount);
            }
        } catch (e) { }
    }

    function checkItemInvoked(eventObject) {
        eventObject.detail.itemPromise.done(function (invokedItem) {
            var _item = invokedItem.data;
            var _checked = !$("#-check-item-" + _item.id + " .checkbox").hasClass("checked");
            checkItem(_item.id, _checked);
            if (itemStore.getCheckedCount(currentListId) > 0) {
                $('#-check-item-reset').show();
            }
            else {
                $('#-check-item-reset').hide();
            }
        });
    }

    function checkItemSelectionchanged() {
        try {
            listCount = checkListsControl.selection.count();
            itemCount = checkItemsControl.selection.count();

            if (listCount > 0 && itemCount > 0) {
                checkListsControl.selection.clear();
            }
            else {
                adjustAppBar(listCount + itemCount);
            }
        } catch (e) { }
    }

    function clearSelection() {
        checkListsControl.selection.clear();
        checkItemsControl.selection.clear();
        adjustAppBar(0);
    }

    function editSelection() {
        if (listCount > 0) {
            editList();
        }
        if (itemCount > 0) {
            editItem();
        }
    }

    function deleteItems() {
        var i;
        if (listCount > 0) {
            getSelectedLists().then(function () {
                for (i = 0; i < selectedLists.length; i++) {
                    listStore.deleteList(selectedLists[i].id);
                    if (selectedLists[i].id == currentListId) {
                        itemsShowed = false;
                        $('#-check-item-add').hide();
                        $('.-check-list-arrow').hide();
                        showItemList(-1);
                    }
                }
                showLists();
                adjustAppBar(0);
                listCount = 0;
            }, function (e) { });
        }
        else if (itemCount > 0) {
            getSelectedItems().then(function () {
                for (i = 0; i < selectedItems.length; i++) {
                    itemStore.deleteItem(selectedItems[i].id);
                }
                showItemList(currentListId);
                adjustAppBar(0);
                itemCount = 0;
            }, function (e) { });
        }
    }

    function addList() {
        appBar.sticky = true;

        var afterInput = function () {
            var _name = _dlg.getValue().trim();
            if (_name != '') {
                var _newList = listStore.add({ name: _name, editing: false });
                currentListId = _newList[0].data.id;
                currentListName = _name;
                listStore.sync();
                showLists();

                var _intervalHandler = setInterval(function () {
                    if ($('.-check-list-arrow').length > 0) {
                        clearInterval(_intervalHandler);
                        itemsShowed = true;
                        $('.-check-list-arrow').hide();
                        $('#-check-list-' + currentListId + ' .-check-list-arrow').show();
                        showItemList(currentListId);
                        adjustAppBar(0, true);
                    }
                }, 100);
            }
            _dlg.close();
        };

        var _dlg = createInputDialog({
            title: Utils.getStr('add_list_title'),
            buttons: [{
                title: Utils.getStr('add'),
                handler: afterInput
            }, {
                title: Utils.getStr('cancel'),
                handler: function () {
                    _dlg.close();
                }
            }],
            enter: afterInput
        });
    }

    function addItem() {
        appBar.sticky = false;
        appBar.hide();

        var _count = 0;

        var afterInput = function () {
            var _name = _dlg.getValue().trim();
            if (_name != '') {
                itemStore.add({ itemname: _name, listId: currentListId, isChecked: false, editing: false });
                itemStore.sync();
                showItemList(currentListId);
                _count++;
                var _info = _count + ' ' + Utils.getStr('add_info_odd');
                if (_count > 1) {
                    _info = _count + ' ' + Utils.getStr('add_info_plural');
                }
                _dlg.showInfo(_info);
            }
            _dlg.clear();
        };

        var _dlg = createInputDialog({
            title: Utils.getStr('add_item_title'),
            buttons: [{
                title: Utils.getStr('add'),
                handler: afterInput
            }, {
                title: Utils.getStr('cancel'),
                handler: function () {
                    _dlg.close();
                }
            }],
            enter: afterInput
        });
    }

    function resetAll() {
        for (i = 0; i < checkItems.length; i++) {
            checkItem(checkItems[i].id, false);
        }
        $('#-check-item-reset').hide();
    }

    function doAppBarShow() {
        var _appBar = document.getElementById("-check-list-bar");
        var _appBarHeight = _appBar.offsetHeight;

        if (_appBar.winControl.sticky) {
            var listViewTargetHeight = "calc(100% - " + _appBarHeight + "px)";
            var transition = {
                property: 'height',
                duration: 367,
                timing: "cubic-bezier(0.1, 0.9, 0.2, 0.1)",
                to: listViewTargetHeight
            };
            $('#-check-list, #-check-item-list').css('height', listViewTargetHeight);
        }
    }

    function doAppBarHide() {
        var _appBar = document.getElementById("-check-list-bar");

        if (_appBar.winControl.sticky) {
            var listViewTargetHeight = "100%";
            var transition = {
                property: 'height',
                duration: 367,
                timing: "cubic-bezier(0.1, 0.9, 0.2, 0.1)",
                to: listViewTargetHeight
            };
            $('#-check-list, #-check-item-list').css('height', listViewTargetHeight);
        }
    }

    // private functions
    function initAppBar() {
        try {
            appBar = document.getElementById("-check-list-bar").winControl;

            addListBtn = document.getElementById('-check-list-add-list');
            addItemBtn = document.getElementById('-check-list-add-item');
            clearSelectBtn = document.getElementById('-check-list-clear-selection');
            editBtn = document.getElementById('-check-list-edit-name');
            deleteBtn = document.getElementById('-check-list-delete');

            appBar.hideCommands([addItemBtn, clearSelectBtn, editBtn, deleteBtn]);

            addListBtn.addEventListener("click", addList, false);
            addItemBtn.addEventListener("click", addItem, false);
            clearSelectBtn.addEventListener("click", clearSelection, false);
            editBtn.addEventListener("click", editSelection, false);
            deleteBtn.addEventListener("click", deleteItems, false);

            appBar.addEventListener("beforeshow", doAppBarShow, false);
            appBar.addEventListener("beforehide", doAppBarHide, false);
        } catch (e) { }
    }

    function initHandler() {
        try {
            document.getElementById("-check-item-reset").addEventListener("click", resetAll, false);
            $('#check-list-main div.homeBtn').click(function () {
                WinJS.Navigation.back();
            });
        } catch (e) { }
    }

    function showLists() {
        checkLists = listStore.getLists();

        checkListsControl.itemDataSource = new WinJS.Binding.List(checkLists).dataSource;
        checkListsControl.itemTemplate = checkListTemplate;//document.getElementById("-check-list-template");
        checkListsControl.forceLayout();

        checkListsControl.addEventListener("iteminvoked", checkListInvoked, false);
        checkListsControl.addEventListener("selectionchanged", checkListSelectionchanged, false);

        if(itemsShowed){
            var _intervalHandler = setInterval(function () {
                if ($('.-check-list-arrow').length > 0) {
                    clearInterval(_intervalHandler);
                    $('#-check-list-' + currentListId + ' .-check-list-arrow').show();
                }
            }, 100);
        }
    }

    function showItemList(id) {
        checkItems = itemStore.getItems(id);

        checkItemsControl.itemDataSource = new WinJS.Binding.List(checkItems).dataSource;
        checkItemsControl.itemTemplate = checkListItemTemplate;
        checkItemsControl.addEventListener("iteminvoked", checkItemInvoked, false);
        checkItemsControl.addEventListener("selectionchanged", checkItemSelectionchanged, false);
        checkItemsControl.forceLayout();

        if (itemStore.getCheckedCount(id) > 0) {
            $('#-check-item-reset').show();
        }
        else {
            $('#-check-item-reset').hide();
        }
    }

    function checkItem(id, checked) {
        var _index = itemStore.findExact('id', id);
        var _checkControl = $("#-check-item-" + id + " .checkbox");
        var _r;
        if (_index != -1) {
            _r = itemStore.getAt(_index);
            if (_r.data.isChecked == checked) {
                return;
            }
            _r.data.isChecked = checked;
            _r.setDirty();
            _r.save();
        }
        itemStore.sync();

        if (checked) {
            _checkControl.addClass("checked");
        } else {
            _checkControl.removeClass("checked");
        }
    }

    function getSelectedLists() {
        return new WinJS.Promise(function (c, e) {
            checkListsControl.selection.getItems().done(function (items) {
                selectedLists = [];
                var i;

                for (i = 0; i < items.length; i++) {
                    selectedLists.push(items[i].data);
                }
                c(selectedLists);
            }, e);
        });
    }

    function getSelectedItems() {
        return new WinJS.Promise(function (c, e) {
            checkItemsControl.selection.getItems().done(function (items) {
                selectedItems = [];
                var i;

                for (i = 0; i < items.length; i++) {
                    selectedItems.push(items[i].data);
                }
                c(selectedItems);
            }, e);
        });
    }

    function adjustAppBar(totalCount, showAppBar) {
        if(totalCount == 0){
            appBar.showCommands([addListBtn]);
            appBar.hideCommands([clearSelectBtn, editBtn, deleteBtn]);
            if (itemsShowed) {
                appBar.showCommands([addItemBtn]);
            }
            else {
                appBar.hideCommands([addItemBtn]);
            }
            if (!showAppBar) {
                appBar.hide();
                appBar.sticky = false;
            }
        }
        else if (totalCount == 1) {
            appBar.hideCommands([addListBtn, addItemBtn]);
            appBar.showCommands([clearSelectBtn, editBtn, deleteBtn]);
            appBar.sticky = true;
            appBar.show();
        }
        else {
            appBar.hideCommands([addListBtn, addItemBtn, editBtn]);
            appBar.showCommands([clearSelectBtn, deleteBtn]);
            appBar.sticky = true;
            appBar.show();
        }
    }

    function editList() {
        getSelectedLists().then(function () {
            var _list = selectedLists[0];
            var afterInput = function () {
                var _name = _dlg.getValue().trim();
                if (_name != '') {
                    listStore.editName(_list.id, _name);
                }
                showLists();
                listCount = 0;
                adjustAppBar(0);
                _dlg.close();
            };
            var _dlg = createInputDialog({
                title: Utils.getStr('edit_title') + ' ' + _list.name,
                originalValue: _list.name,
                buttons: [{
                    title: Utils.getStr('save'),
                    handler: afterInput
                }, {
                    title: Utils.getStr('cancel'),
                    handler: function () {
                        _dlg.close();
                    }
                }],
                enter: afterInput
            });
        }, function (e) { });
    }

    function editItem() {
        getSelectedItems().then(function () {
            var _item = selectedItems[0];
            var afterInput = function () {
                var _name = _dlg.getValue().trim();
                if (_name != '') {
                    itemStore.editName(_item.id, _name);
                }
                showItemList(currentListId);
                itemCount = 0;
                adjustAppBar(0);
                _dlg.close();
            };
            var _dlg = createInputDialog({
                title: Utils.getStr('edit_title') + ' ' + _item.itemname,
                originalValue: _item.itemname,
                buttons: [{
                    title: Utils.getStr('save'),
                    handler: afterInput
                }, {
                    title: Utils.getStr('cancel'),
                    handler: function () {
                        _dlg.close();
                    }
                }],
                enter: afterInput
            });
        }, function (e) { });
    }
})();
